<template>
  <view class="wrap">
    <uv-gap height="20rpx" bgColor="#F0F0F0"></uv-gap>
    <view class="box">
      <view class="title pb30">直播封面</view>
      <view class="upload" @click="chooseImage">
        <view class="nowImage" v-if="opt.thumb">
          <image :src="setUrl(opt.thumb)" mode="aspectFill" class="img"></image>
        </view>
        <image src="../../../static/hintFromImage.png" class="img" v-else></image>
      </view>
      <view class="item">
        <view class="left">标题</view>
        <view class="test">
          <uv-input placeholder="请填写直播标题" v-model="opt.title" :readonly="type=='look'" maxlength='15' border="none" placeholderStyle='font-size: 28rpx; color: rgba(0, 0, 0, .15);text-align: right;' font-size="28rpx" color="#000" input-align="right"></uv-input>
        </view>
      </view>
      <view class="item" :class="{ not: type == 'back' }" @click="openStartTime">
        <view class="left">开始时间</view>
        <view class="test">
          {{ opt.start_at }}
        </view>
      </view>
      <view class="item" :class="{ not: type == 'back' }" @click="openEndTime">
        <view class="left">结束时间</view>
        <view class="test">
          {{ opt.end_at }}
        </view>
      </view>
      <template v-if="tagList.length">
        <view class="title pb30">直播分类<text class="desc">*最多可选择三个分类</text></view>
        <view class="tips">
          <view class="test" :class="{ active: opt.tags.indexOf(item.id) >= 0 }" v-for="(item, index) in tagList" :key="index" @click="tagClick(item)">{{ item.name }}</view>
        </view>
      </template>
      <view class="title pb30">直播介绍</view>
      <uv-textarea v-model="opt.profile" :disabled="type=='look'" placeholder="请输入直播介绍" height="200rpx" maxlength='500' border='surround' :customStyle="{borderRadius: '12rpx', backgroundColor: '#FFFFFF'}" :textStyle="{fontSize: '24rpx', color: '#333'}" placeholderStyle='font-size: 24rpx; color: rgba(0, 0, 0, .15)'></uv-textarea>
      <view class="item">
        <view class="left">是否收费</view>
        <view class="radio">
          <view class="check" @click="tabFree(0)">
            <image src="../../../static/radio-off.png" class="img" v-if="opt.is_free == 1"></image>
            <image src="../../../static/radio-on.png" class="img" v-if="opt.is_free == 0"></image>
            <view class="test">是</view>
          </view>
          <view class="check" @click="tabFree(1)">
            <image src="../../../static/radio-off.png" class="img" v-if="opt.is_free == 0"></image>
            <image src="../../../static/radio-on.png" class="img" v-if="opt.is_free == 1"></image>
            <view class="test">否</view>
          </view>
        </view>
      </view>
      <view class="item" v-if="opt.is_free == 0">
        <view class="left">收费金额</view>
        <view class="test">
          <uv-input type='number' placeholder="请填写收费金额" v-model="opt.price" :readonly="type=='look'" border="none" placeholderStyle='font-size: 28rpx; color: rgba(0, 0, 0, .15);text-align: right;' font-size="28rpx" color="#000" input-align="right"></uv-input>
        </view>
      </view>
      <view class="item" :class="{ not: type == 'back' }" @click="openPick">
        <view class="left">参会权限</view>
        <view class="test">
          {{ typeList[opt.join_permission] }}
        </view>
      </view>
      <view class="item" :class="{ not: opt.join_permission == 1 }">
        <view class="left">是否需要报名</view>
        <view class="radio">
          <view class="check" @click="tabEnroll(0)">
            <image src="../../../static/radio-off.png" class="img" v-if="opt.need_enroll == 1"></image>
            <image src="../../../static/radio-on.png" class="img" v-if="opt.need_enroll == 0"></image>
            <view class="test">无需报名</view>
          </view>
          <view class="check" @click="tabEnroll(1)">
            <image src="../../../static/radio-off.png" class="img" v-if="opt.need_enroll == 0"></image>
            <image src="../../../static/radio-on.png" class="img" v-if="opt.need_enroll == 1"></image>
            <view class="test">需要报名</view>
          </view>
        </view>
      </view>
      <view class="item" v-if="opt.need_enroll == 1">
        <view class="left">用户报名是否免审</view>
        <view class="radio">
          <view class="check" @click="tabNeed(0)">
            <image src="../../../static/radio-off.png" class="img" v-if="opt.need_examine == 1"></image>
            <image src="../../../static/radio-on.png" class="img" v-if="opt.need_examine == 0"></image>
            <view class="test">免审</view>
          </view>
          <view class="check" @click="tabNeed(1)">
            <image src="../../../static/radio-off.png" class="img" v-if="opt.need_examine == 0"></image>
            <image src="../../../static/radio-on.png" class="img" v-if="opt.need_examine == 1"></image>
            <view class="test">需要审核</view>
          </view>
        </view>
      </view>
      <view class="title pb30">会议文档</view>
      <view class="upLoadFile">
        <button class="btn" hover-class="none" :disabled="type == 'look'" @click="chooseFile">{{ opt.document_url ? '已上传' : '请选择文档' }}</button>
      </view>
    </view>
    <template v-if="type != 'look'">
      <view class="conet">*审核通过后无法修改直播申请</view>
      <view class="foot">
        <button class="btn" hover-class="none" :disabled='disabled' @click="keyUp">提交申请</button>
      </view>
    </template>
    <uv-safe-bottom></uv-safe-bottom>
    
    <uv-modal ref="modal" title="需要文件访问权限" showCancelButton confirmColor='#E43222' confirmText='去授权' @confirm="fileConfirm">
      <view>
        您还未授权本应用读取文件。为保证您可以正常上传文件，请在权限设置页面打开文件访问权限（不同手机厂商表述可能略有差异）请根据自己手机品牌设置
      </view>
    </uv-modal>
    
    <uv-datetime-picker ref="start" v-model="startValue" mode="datetime" confirmColor='#E43222' :minDate='startTime' @confirm="startConfirm"></uv-datetime-picker>
    <uv-datetime-picker ref="end" v-model="endValue" mode="datetime" confirmColor='#E43222' :minDate='endTime' @confirm="endConfirm"></uv-datetime-picker>
    <uv-picker ref="picker" :columns="columns" keyName="label" confirmColor='#E43222' @confirm="pickConfirm"></uv-picker>
    
    <action ref="actionPhoto" @click="getImageUrl"></action>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { choose, setUrl, setUpload, toast } from '@/common';
import { onLoad, onReady } from '@dcloudio/uni-app';
import { get, post } from '@/api';
import { timeFormat } from '@/uni_modules/uv-ui-tools/libs/function/index.js';
// #ifdef APP-PLUS
const lemonjkFileSelect = uni.requireNativePlugin('lemonjk-FileSelect');
// #endif

const actionPhoto = ref(null);
const modal = ref(null);
const start = ref(null);
const end = ref(null);
const picker = ref(null);
let columns = ref([
  [{ label: '专场', id: 1 }, { label: '机构', id: 2 }, { label: '公开', id: 3 }]
]);
const typeList = ref({
  1: '专场',
  2: '机构',
  3: '公开'
})
const titleType = {
  add: '发起直播',
  edit: '修改直播',
  back: '管理回放',
  look: '查看详情',
}
let tagList = ref([]);
let startTime = ref( new Date(new Date().getTime() + 1800000).getTime() );
let endTime = ref( new Date(new Date().getTime() + 5400000).getTime() );
let startValue = ref('');
let endValue = ref('');
let opt = ref({
  thumb: '',
  title: '',
  start_at: '',
  end_at: '',
  profile: '',
  is_free: 0,
  price: '',
  tags: [],
  join_permission: '',
  need_enroll: 1,
  need_examine: 1,
  document_name: '',
  document_url: ''
});
let disabled = ref(false);
let type = ref('');
let id = '';
let ros = '';

onLoad((option) => {
  if(option.type){
    type.value = option.type;
  }
  uni.setNavigationBarTitle({
  	title: titleType[option.type]
  });
  if(option.id){
    id = option.id;
    getData();
  }
  getTypeList();
})
onReady(() => {
  start.value.setFormatter(formatter)
})

function keyUp(){
  if(type.value == 'look') return;
  
  let value = opt.value;
  if(!value.thumb) return toast('请上传封面图');
  if(!value.title) return toast('请输入标题');
  if(!value.start_at) return toast('请选择开始日期');
  if(!value.end_at) return toast('请选择结束日期');
  if(!value.tags.length) return toast('请选择直播分类');
  if(!value.profile) return toast('请输入直播介绍');
  if(value.is_free == 1) opt.value.price = '';
  if(value.is_free == 0 && !value.price) return toast('请输入收费金额');
  if(!value.join_permission) return toast('请选择参会权限');
  
  disabled.value = true;
  let params = {
    thumb: value.thumb,
    title: value.title,
    start_at: value.start_at,
    end_at: value.end_at,
    profile: value.profile,
    is_free: value.is_free,
    tags: value.tags.toString(),
    join_permission: value.join_permission,
    need_enroll: value.need_enroll,
    need_examine: value.need_examine,
    document_name: value.document_name,
    document_url: value.document_url
  }
  if(!value.is_free) {
    params.price = value.price;
  }else{
    params.price = 0;
  }
  let url = '';
  if(type.value == 'add'){
    url = '/api/Live/newLive';
  }else{
    params.lessonLiveId = id;
    url = '/api/Live/editLive';
  }
  console.log(params);
  post(url, params).then(res => {
    disabled.value = false;
    if(res.code == 1){
      toast('操作成功');
      setTimeout(() => {
        uni.navigateBack({
          delta: 1
        });
      },1000)
    }
  })
}
function getData(){
  get('/api/Live/getDetails', { lessonLiveId: id }).then(res => {
    if(res.code == 1){
      const data = res.data;
      opt.value = data;
      opt.value.tags = data.tagList.map(e => e.id);
    }
  })
}
function getTypeList(){
  get('/api/Live/getTags').then(res => {
    if(res.code == 1){
      const data = res.data;
      tagList.value = data;
    }
  })
}
// 上传图片
function chooseImage(){
  // 查看详情,不能操作
  if(type.value == 'look') return;
  actionPhoto.value.open();
}
function getImageUrl(url){
  opt.value.thumb = url;
}
function fileConfirm(){
  // 跳转到应用设置页
  lemonjkFileSelect.gotoSetting();  
}
// 上传文件
function chooseFile(){
  // #ifndef APP-PLUS
  return toast('请打开APP上传');
  // #endif
  // 查看详情,不能操作
  if(type.value == 'look') return;
  lemonjkFileSelect.showPicker({
    mimeType: 'application/pdf',
    utisType: 'public.composite-content'
  }, res => {
    let os = uni.$uv.os();
    if(os == 'android'){
      if(res.code == 1001){
        modal.value.open();
      }else if(res.code == 0){
        console.log(res.files[0]);
        
        setUpload([res.files[0].filePath]).then(file => {
          opt.value.document_url = setUrl(file);
          let filename = res.files[0].fileName;
          let lastIndex = filename.lastIndexOf('.');
          let basename = filename.substring(0, lastIndex);
          opt.value.document_name = basename;
        })
      }else{
        toast(res.detail)
      }
    }else{
      if(res.code == 0){
        setUpload([res.files[0].filePath]).then(file => {
          opt.value.document_url = file;
          opt.value.document_name = res.files[0].fileName;
        })
      }else{
        toast(res.detail)
      }
    }
  })
}
// 参会权限弹窗确认
function pickConfirm({ value }){
  if(value[0].id == 1){
    opt.value.need_enroll = 1;
  }
  opt.value.join_permission = value[0].id;
}
// 打开参会权限弹窗
function openPick(){
  // 管理回放和查看详情,不能操作
  if(type.value == 'back' || type.value == 'look') return;
  picker.value.open();
}
// 开始时间确认
function startConfirm({ value }){
  opt.value.start_at = timeFormat(value, 'yyyy-mm-dd hh:MM');
}
// 弹出开始时间选择器
function openStartTime(){
  // 管理回放和查看详情,不能操作
  if(type.value == 'back' || type.value == 'look') return;
  start.value.open();
}
// 结束时间确认
function endConfirm({ value }){
  if(!opt.value.start_at) return toast('请选择开始时间');
  if(!isTimes(opt.value.start_at, value)) return toast('结束时间必须大于开始时间1小时');
  opt.value.end_at = timeFormat(value, 'yyyy-mm-dd hh:MM');
}
// 弹出结束时间选择器
function openEndTime(){
  // 管理回放和查看详情,不能操作
  if(type.value == 'back' || type.value == 'look') return;
  end.value.open();
}
// 格式化日期
function formatter(type, value) {
  const typeDate = {
    year: '年',
    month: '月',
    day: '日',
    hour: '时',
    minute: '分'
  }
  return `${value}${typeDate[type]}`
  return value
}
// 直播分类选择
function tagClick(row){
  // 查看详情,不能操作
  if(type.value == 'look') return;
  let index = opt.value.tags.indexOf(row.id);
  if(opt.value.tags.length >= 3 && index == -1) return toast('最多选择三个');
  if(index >= 0){
    opt.value.tags.splice(index, 1);
  }else{
    opt.value.tags.push(row.id);
  }
}
// 是否收费
function tabFree(index){
  if(type.value == 'look') return;
  opt.value.is_free = index;
}
// 是否免审
function tabNeed(index){
  if(type.value == 'look') return;
  opt.value.need_examine = index;
}
// 是否需要报名
function tabEnroll(index){
  if(type.value == 'look' || opt.value.join_permission == 1) return;
  opt.value.need_enroll = index;
}
function isTimes(dateInput, timestamp) {
  var date = new Date(dateInput); // 确保传入的日期是Date对象
  var oneHourAfterDate = new Date(date.getTime() + 3600000); // 给定日期加上1小时
  var oneHourAfterTimestamp = oneHourAfterDate.getTime(); // 获取1小时后的时间戳
  
  return timestamp > oneHourAfterTimestamp; // 判断传入的时间戳是否大于给定日期1小时后的时间戳
}
</script>

<style lang="scss" scoped>
  .foot{
    padding: 30rpx 150rpx;
  }
  .conet{
    text-align: center;
    color: #E43222;
    font-size: 26rpx;
    padding-top: 80rpx;
  }
  .box{
    width: 100%;
    padding: 0 30rpx;
    .item{
      width: 100%;
      padding: 35rpx 0;
      border-bottom: 1px solid rgba($color: #979797, $alpha: .25);
      display: flex;
      align-items: center;
      justify-content: space-between;
      &.not{
        & > .test, .radio .check .test{
          color: rgba($color: #979797, $alpha: .45);
        }
      }
      .radio{
        display: flex;
        align-items: center;
        .check{
          display: flex;
          align-items: center;
          margin-right: 80rpx;
          &:last-child{
            margin-right: 0;
          }
          .test{
            font-weight: 400;
            font-size: 26rpx;
            color: #000000;
            padding-left: 14rpx;
          }
          .img{
            width: 22rpx;
            height: 22rpx;
          }
        }
      }
      .left{
        font-weight: 400;
        font-size: 28rpx;
        color: #000000;
      }
      & > .test{
        font-size: 28rpx;
      }
    }
    .upLoadFile{
      padding-top: 10rpx;
      padding-bottom: 20rpx;
      .btn{
        height: 72rpx;
        line-height: 72rpx;
        background-image: none;
        background-color: rgba($color: #E43222, $alpha: .16);
        color: #E43222;
        font-size: 28rpx;
        &[disabled]:not([type]){
          color: #FFFFFF;
          background-color: rgba($color: #000, $alpha: .16);
        }
      }
    }
    .tips{
      padding-top: 20rpx;
      padding-bottom: 30rpx;
      border-bottom: 1px solid rgba($color: #979797, $alpha: .25);
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .test{
        font-weight: 400;
        font-size: 28rpx;
        color: #2B2B2B;
        height: 80rpx;
        line-height: 80rpx;
        padding: 0 20rpx;
        background: #F5F5F5;
        border-radius: 16rpx;
        margin-right: 20rpx;
        &.active{
          background-color: rgba(228, 50, 34, 0.16);
          color: #E43222;
        }
      }
    }
    .upload{
      width: 337rpx;
      height: 216rpx;
      font-size: 0;
      margin-bottom: 52rpx;
      .nowImage{
        width: 337rpx;
        height: 216rpx;
        font-size: 0;
        border-radius: 12rpx;
        overflow: hidden;
      }
    }
    .title{
      font-weight: 500;
      font-size: 28rpx;
      color: #000000;
      padding-top: 50rpx;
      &.pb30{
        padding-bottom: 30rpx;
      }
      .desc{
        font-size: 24rpx;
        padding-left: 20rpx;
        color: rgba($color: #979797, $alpha: .45);
      }
    }
  }
</style>